<?php

class Domain_Admin {

    public function checkAdmin($username) {
        $model = new Model_Admin();
        $rs = $model->getByUserName($username);
        return $rs;

    }

    public function getAdminById($userid) {
        $model = new Model_Admin();
        $rs = $model->getByUserId($userid);
        return $rs;

    }

    public function updatelastlogintime($username) {
        $model = new Model_Admin();
        $rs = $model->updatelastlogintime($username);
        return $rs;

    }

    public function getlist($keyword = null) {
        $model = new Model_Admin();
        $where=[];
        if ($keyword) $where ["name like ?"] = '%'.$keyword.'%';
        $rs = $model->getlist($where);
        return $rs;

    }

    public function add($username, $password, $nickname, $email,$rules) {
        if ($this->checkAdmin($username)) {
            DI()->response->setData(null);
            throw new PhalApi_Exception('用户名已存在', 1004);
        }
        $encryption = DI()->helper->createRandStr(8);
        $data = [
            "username"      => $username,
            "password"      => md5($password . $encryption),
            "encryption"    => $encryption,
            "nickname"      => $nickname,
            "email"         => $email,
            "rules"         => $rules,
            "lastlogintime" => DI()->helper->getTime(),
        ];
        $model = new Model_Admin();
        return $model->add($data);
    }

    public function update($userid, $password, $nickname, $email,$rules) {
        $data = [];
        if (!$userid) {
            return false;
        }


        if ($password) {
            $encryption = DI()->helper->createRandStr(8);
            $data['password'] = md5($password . $encryption);
            $data['encryption'] = $encryption;
        }
        if ($nickname) {
            $data['nickname'] = $nickname;
        }
        if ($email) {
            $data['email'] = $email;
        }
        if ($rules) {
            $data['rules'] = $rules;
        }

        $model = new Model_Admin();
        return $model->update($data, $userid);
    }

    public function delete($userid) {
        if (!$userid) {
            return false;
        }
        $model = new Model_Admin();
        return $model->deleteByUserId($userid);

    }
}
